package com.zq.sysuser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zq.sysuser.dao.dto.UserRoleDto;
import com.zq.sysuser.dao.entity.Role;
import com.zq.sysuser.dao.entity.UserRole;
import com.zq.sysuser.mapper.RoleMapper;
import com.zq.sysuser.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zq.sysuser.service.IUserRoleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张乔
 * @since 2024-04-26
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    //查询角色列表，分页查询。num、size和角色名
    @Override
    public PageInfo<Role> findByPage(String roleName, Integer pageNum, Integer pageSize) {

        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        //查询条件
        wrapper.like(StringUtils.hasText(roleName),Role::getName, roleName)
                .orderByDesc(Role::getId);
//        两个操作最好放在一起
        PageHelper.startPage(pageNum, pageSize);
        List<Role> roleList = this.list(wrapper);


        PageInfo<Role> page = new PageInfo<>(roleList);
        return page;
    }

//    //添加角色
    @Override
    public void addRole(Role role) {

        Role role1 = this.getOne(new LambdaQueryWrapper<Role>()
                .eq(StringUtils.hasText(role.getName()), Role::getName, role.getName()));
        if (role1 != null) {
            throw new RuntimeException("角色已存在");
        }
        this.save(role);
    }

//    //修改角色
    @Override
    public void updateRole(Role role) {
        Role role1 = this.getById(role.getId());
        if (role1 == null) {
            throw new RuntimeException("角色不存在");
        }
        if (role1.getName().equals(role.getName())) {
            throw new RuntimeException("新角色名与旧角色名相同");
        }

        this.updateById(role);
    }


    //根据id删除角色
    @Override
    public void deleteById(Integer id) {

        this.removeById(id);

    }


    @Resource
    private IUserRoleService userRoleService;

    //分配角色给用户
    @Override
    public void doAssign(UserRoleDto userRoleDto) {
        // 删除之前的所有的用户所对应的角色数据

        log.info("分配角色给用户");
        userRoleService.remove(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userRoleDto.getUserId()));
        // 分配新的角色数据
        List<Integer> roleIdList = userRoleDto.getRoleIdList();

        roleIdList.forEach(roleId -> {
            UserRole userRole = new UserRole();
            userRole.setUserId(userRoleDto.getUserId());
            userRole.setRoleId(roleId);
            userRoleService.save(userRole);
        });
    }



    //用户拥有角色数据回显
    @Override
    public Map<String, Object> findAllRoles(Integer userId) {

        // 查询所有的角色数据

        List<Role> roleList = this.list();

        // 查询当前登录用户的角色数据
        List<UserRole> userRoleList = userRoleService.
                list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));

        List<Integer> roleIds=new ArrayList<>();
        userRoleList.forEach(userRole -> {
            // 获取当前用户的所有角色id
          roleIds.add(userRole.getRoleId());
        });


        // 构建响应结果数据
        Map<String , Object> resultMap = new HashMap<>() ;
        resultMap.put("allRolesList" , roleList) ;
        resultMap.put("sysUserRoles", roleIds);

        return resultMap;
    }


}
